package com.haochang.chunkvod.controller.activity;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONObject;

import com.haochang.base.BaseActivity;
import com.haochang.base.BaseTextView;
import com.haochang.base.OnBaseClickListener;
import com.haochang.chunkvod.R;
import com.haochang.chunkvod.app.common.VodConstant;
import com.haochang.chunkvod.app.common.intent.IntentCode;
import com.haochang.chunkvod.app.common.intent.IntentKey;
import com.haochang.chunkvod.app.utils.HelperUtils;
import com.haochang.chunkvod.app.utils.PackageManagerUtil;
import com.haochang.chunkvod.app.utils.RequestPermissionsUtil;
import com.haochang.chunkvod.app.utils.ToastUtils;
import com.haochang.chunkvod.app.utils.UpdateUtil;
import com.haochang.chunkvod.controller.activity.hostess.HostessHomeActivity;
import com.haochang.chunkvod.controller.activity.order.CustomActivity;
import com.haochang.chunkvod.controller.activity.order.OrderHomePageActivity;
import com.haochang.chunkvod.model.cash.CashData;
import com.haochang.chunkvod.model.cash.PrintEnum;
import com.haochang.chunkvod.model.cash.PrintInfo;
import com.haochang.chunkvod.model.custom.CustomDialogData;
import com.haochang.chunkvod.model.order.OrderData;
import com.haochang.chunkvod.tools.vod.log.Logger;
import com.haochang.chunkvod.tools.vod.other.DownLoadObserver;
import com.haochang.chunkvod.tools.vod.thread.PrintThread;
import com.haochang.chunkvod.tools.vod.thread.ThreadPoolUtil;
import com.haochang.chunkvod.view.vod.activity.SingleInputActivity;
import com.haochang.chunkvod.view.vod.popupWindow.VodPopWindow;
import com.haochang.chunkvod.view.vod.title.TitleView;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;

/**
 * @author qintao
 *         created at 2016/5/31 19:01
 *         vod首页
 */

public class VodActivity extends BaseActivity implements ActivityCompat.OnRequestPermissionsResultCallback
{
	private RelativeLayout order_div;
	private RelativeLayout cash_div;
	private RelativeLayout clients_div;
	private RelativeLayout store_div;
	private TitleView titleView;
	private BaseTextView tv_version;

	private long onKeyDown_BACK_TouchTime = 0;
	private final long MAX_TIME = 3000;
	private CashData cashData;
	private CustomDialogData customDialogData;
	private OrderData orderData;
	private boolean isGetPrintInfo = false;
	private ProgressHandler progressHandler = new ProgressHandler(this);

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
	}

	@Override
	public void receiveParam()
	{
	}

	@Override
	public void initData()
	{
		orderData = new OrderData(VodActivity.this);
		cashData = new CashData(VodActivity.this);
		customDialogData = new CustomDialogData(VodActivity.this);
		//修改：开启版本检测 2016/12/23
		UpdateUtil.getInstanse().requestUpdateVersion(VodActivity.this, progressHandler);//检查版本更新
	}

	@Override
	public void initViews()
	{
		setContentView(R.layout.activity_vod);
		titleView = (TitleView) findViewById(R.id.titleView);
		titleView.setTitle("首页").setLeftIconVISIBLE(false).setTitleOnClickListener(new TitleView.ITitleOnClickListener()
		{
			@Override
			public void onBackClick()
			{
			}

			@Override
			public void onDoneClick()
			{
				List<String> list = new ArrayList<String>();
				//list.add("修改密码");
				list.add("退出登录");
				int location[] = new int[2];
				ImageView img = (ImageView) titleView.findViewById(R.id.img_operates);
				img.getLocationOnScreen(location);
				int x = location[0];
				final VodPopWindow pop = new VodPopWindow(VodActivity.this, list);
				pop.showPopupWindow(titleView, x);
				pop.setPopWindowListListener(new VodPopWindow.OnPopWindowListListener()
				{
					@Override
					public void onSelectItem(int position)
					{
						switch (position)
						{
						//case 0:
						//goToPasswordModify();
						//break;
						case 0:
							loginOut();
							break;
						default:
							break;
						}
					}
				});
			}
		});
		order_div = (RelativeLayout) findViewById(R.id.order_div);
		order_div.setOnClickListener(mOnBaseClickListener);
		order_div.setOnTouchListener(onTouchListener);
		cash_div = (RelativeLayout) findViewById(R.id.cash_div);
		cash_div.setOnClickListener(mOnBaseClickListener);
		cash_div.setOnTouchListener(onTouchListener);
		clients_div = (RelativeLayout) findViewById(R.id.clients_div);
		clients_div.setOnClickListener(mOnBaseClickListener);
		clients_div.setOnTouchListener(onTouchListener);
		store_div = (RelativeLayout) findViewById(R.id.store_div);
		store_div.setOnClickListener(mOnBaseClickListener);
		store_div.setOnTouchListener(onTouchListener);
		tv_version = (BaseTextView) findViewById(R.id.tv_version);
		tv_version.setText(String.valueOf("当前版本：" + PackageManagerUtil.getInstance().getVersion(VodActivity.this)));
		orderData.requestBaseInfo();
	}

	private OnBaseClickListener mOnBaseClickListener = new OnBaseClickListener()
	{
		@Override
		public void onBaseClick(View v)
		{
			switch (v.getId())
			{
			case R.id.order_div:
				String view = HelperUtils.getHelperAppInstance().getSValue("isListView", VodConstant.GRIDVIEW);
				if (!TextUtils.isEmpty(view) && view.equals(VodConstant.CUSTOMVIEW))
					startEnterActivity(CustomActivity.class);
				else
					startEnterActivity(OrderHomePageActivity.class);
				break;
			case R.id.cash_div:
				//				isGetPrintInfo = HelperUtils.getHelperInstance().getBValue(IntentKey.IS_GET_PRINT_INFO, false);
				//判断是否用的是P2000的设备
				//				if (!isGetPrintInfo)
				//				{
				//					ToastUtils.showText(VodActivity.this, "获取列印基本信息失败，请重启应用重新获取");
				//				} else
				//				{
				//				if (!DeviceConfig.isUseP2000Device())
				//				{
				//					cashData.requestShift(new CashData.IShiftListener()
				//					{
				//						@Override
				//						public void onRequestSuccess()
				//						{
				//							startEnterActivity(CashHomePageActivity.class);
				//						}
				//
				//						@Override
				//						public void onRequestFail(int errno, String errMsg)
				//						{
				//							ToastUtils.showText(VodActivity.this, errMsg);
				//							if (errno == ServerErrorCodeConfig.SHIFT_OUT_TIME)
				//							{
				//								onShiftClick();
				//							}
				//						}
				//					});
				//				} else
				//				{
				//					ToastUtils.showText(VodActivity.this, "您的设备暂不支持此功能");
				//				}
				//				}
				ToastUtils.showText(VodActivity.this, "此功能暂未开发");
				break;
			case R.id.clients_div:
				//				startEnterActivity(HostessHomeActivity.class);
				ToastUtils.showText(VodActivity.this, "此功能暂未开发");
				break;
			case R.id.store_div:
				ToastUtils.showText(VodActivity.this, "此功能暂未开发");
				break;
			default:
				break;
			}
		}
	};
	private View.OnTouchListener onTouchListener = new View.OnTouchListener()
	{
		@Override
		public boolean onTouch(View v, MotionEvent event)
		{
			switch (event.getAction())
			{
			case MotionEvent.ACTION_DOWN:
				v.getBackground().setAlpha(130);
				break;

			case MotionEvent.ACTION_UP:
				v.getBackground().setAlpha(255);
				break;

			case MotionEvent.ACTION_CANCEL:
				v.getBackground().setAlpha(255);
				break;

			case MotionEvent.ACTION_OUTSIDE:
				v.getBackground().setAlpha(255);
				break;
			default:
				break;
			}
			return false;
		}
	};

	/**
	 * 点击交班
	 */
	private void onShiftClick()
	{
		Intent intent = new Intent(VodActivity.this, SingleInputActivity.class);
		intent.putExtra(IntentKey.CUSTOM_DIALOG_CONTENT_HINT, "请输入密码");
		intent.putExtra(IntentKey.CUSTOM_DIALOG_TITLE, "交班");
		intent.putExtra(IntentKey.BTN_SURE, "确定");
		intent.putExtra(IntentKey.BTN_CANCEL, "取消");
		intent.putExtra(IntentKey.ACTIVITY_ENUM, SingleInputActivity.ActivityEnum.PERMISSION);
		startActivityForResult(intent, IntentCode.SHIFT_REQUEST);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		super.onActivityResult(requestCode, resultCode, data);
		Logger.e("交易成功resultCode:" + resultCode);
		if (requestCode == IntentCode.SHIFT_REQUEST && resultCode == RESULT_OK && data != null)
		{
			//交班操作
			customDialogData.requestShift(new CustomDialogData.IShiftListener()
			{
				@Override
				public void onRequestSuccess(JSONObject jsonObject)
				{
					PrintInfo printInfo = new PrintInfo();
					printInfo.setType(PrintEnum.PRINT_SHIFT.getName());
					printInfo.setContent(jsonObject.optJSONObject("shift").toString());
					ThreadPoolUtil.getInstanceSingleTaskExecutor().submit(new PrintThread(PrintEnum.PRINT_SHIFT, printInfo));
					PrintInfo printInfo2 = new PrintInfo();
					printInfo2.setType(PrintEnum.CASH_MONEY.getName());
					printInfo2.setContent(jsonObject.optJSONObject("gotmoney").toString());
					ThreadPoolUtil.getInstanceSingleTaskExecutor().submit(new PrintThread(PrintEnum.CASH_MONEY, printInfo2));
					loginOutDone();
				}
			});
		}
	}

	public boolean dispatchKeyEvent(KeyEvent event)
	{
		boolean returnValue = false;
		if (event.getAction() == KeyEvent.ACTION_DOWN && event.getKeyCode() == KeyEvent.KEYCODE_BACK)
		{
			returnValue = true;
			long currentTime = System.currentTimeMillis();
			if ((currentTime - onKeyDown_BACK_TouchTime) > MAX_TIME)
			{
				ToastUtils.showText(VodActivity.this, R.string.main_back_hint);
				this.onKeyDown_BACK_TouchTime = currentTime;
			} else
			{
				//返回 Android 系统 HOME 桌面
				Intent intent = new Intent(Intent.ACTION_MAIN);
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				intent.addCategory(Intent.CATEGORY_HOME);
				this.startActivity(intent);
				this.overridePendingTransition(0, 0);
				android.os.Process.killProcess(android.os.Process.myPid());
			}
		} else
			returnValue = super.dispatchKeyEvent(event);
		return returnValue;
	}

	@Override
	protected void onDestroy()
	{
		super.onDestroy();
		if (null != progressHandler)
		{
			progressHandler.removeCallbacksAndMessages(null);
		}
	}

	/**
	 * 防止内存溢出的内部静态handler
	 */
	private static class ProgressHandler extends Handler
	{
		WeakReference<VodActivity> weakReference;

		ProgressHandler(VodActivity activity)
		{
			weakReference = new WeakReference<VodActivity>(activity);
		}

		@Override
		public void handleMessage(Message msg)
		{
			super.handleMessage(msg);
			if (msg.what == DownLoadObserver.MESSAGE_PROGRESS)
			{
				int progress = msg.arg1;
				//				ToastUtils.showText(weakReference.get(), "新进度：" + progress);
				if (progress >= 100)
				{
					String path = (String) msg.obj;
					if (!TextUtils.isEmpty(path))
					{
						UpdateUtil.getInstanse().installAPK(weakReference.get(), path);
					}
				}
			}
		}
	}

	@Override
	public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults)
	{
		super.onRequestPermissionsResult(requestCode, permissions, grantResults);
		if (requestCode == RequestPermissionsUtil.PERMISSION_WRITE_EXTERNAL_STORAGE)
		{
			if ((grantResults.length >= 1) && (grantResults[0] == PackageManager.PERMISSION_GRANTED))
			{
				UpdateUtil.getInstanse().showUpdateDialog(VodActivity.this, progressHandler);
			} else
			{
				ToastUtils.showText(VodActivity.this, "未获取读写存储卡权限");
			}
		}
	}
}
